package com.bdhub.handld;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceFactory {
	// private static final ExecutorServiceFactory factory = new
	// ExecutorServiceFactory();
	private ExecutorService bossPool;// 管理线程，负责重连
	private ExecutorService workPool;// 工作线程，负责心跳

	public ExecutorServiceFactory() {

	}

	// public static ExecutorServiceFactory getInstance() {
	// return factory;
	// }

	// public void init(int bossSize,int workSize) {
	// bossPool = Executors.newFixedThreadPool(bossSize);
	// workPool = Executors.newFixedThreadPool(workSize);
	// }
	public synchronized void initBossPool(int boosSize) {
		destoryBoss();
		bossPool = Executors.newFixedThreadPool(boosSize);
	}

	public synchronized void initWorkPool(int workSize) {
		destoryWork();
		workPool = Executors.newFixedThreadPool(workSize);
	}

	public synchronized void destoryBoss() {
		if (bossPool != null) {
			try {
				// 关闭线程池
				bossPool.shutdownNow();
				// 等待线程中的线程全部结束
				// pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
			} catch (Throwable ex) {
				ex.printStackTrace();
			} finally {
				bossPool = null;
			}
		}
	}

	public synchronized void destoryWork() {
		if (workPool != null) {
			try {
				// 关闭线程池
				workPool.shutdownNow();
				// 等待线程中的线程全部结束
				// pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
			} catch (Throwable ex) {
				ex.printStackTrace();
			} finally {
				workPool = null;
			}
		}
	}

	public synchronized void destory() {
		destoryWork();
		destoryBoss();
	}

	public void executeBoss(Runnable thread) {
		if (null == bossPool) {
			System.err.println("thread bossPool not init");
		}
		bossPool.execute(thread);
	}

	public void executeWorker(Runnable thread) {
		if (null == workPool) {
			System.err.println("thread workPool not init");
		}
		workPool.execute(thread);
	}
}
